package cn.nfwx.tv.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.antfortune.freeline.FreelineCore;
import com.github.moduth.blockcanary.BlockCanary;
import com.github.moduth.blockcanary.BlockCanaryContext;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import cn.nfwx.tv.BuildConfig;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.helper.ActivityHelper;
import cn.nfwx.tv.helper.BuglyHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.UmengPushHelper;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.SharePrefUtil;

/**
 * Created by zb.liu on 2017/10/27.
 */

public class NFWXApplication extends Application implements ActivityHelper.ActivityStatusListener {
    public final static String weixin_appid = "wx54b68c4a5e1a51aa";//微信appid
    private static NFWXApplication instance;
    private static final String grab_appid = "F6DDD8248BBC4B889D286F5C6A53069E";
    private static final String grab_secret = "59020c4af5d8";

    public static NFWXApplication getInstance() {
        return instance;
    }

    //    private P2PSMgr p2PSMgr;
    private IWXAPI iwxapi;
    public static boolean userFreeWifi = true;
    public static boolean isUpdate = true;

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //  EventBus.getDefault().register(this);
        try {
            if (isMainProcess()) {
                instance = this;

                UMConfigure.setLogEnabled(false);
                UMConfigure.init(this, "59b785757f2c744a1d000096", AppUtil.getChannel(this), UMConfigure.DEVICE_TYPE_PHONE,
                        "7258782c9450c5df42de9bfff14b882d");
                registerActivityLifecycleCallbacks(ActivityHelper.getInstance());
                DownloadM3u8Controller.getInstance().refreshAll(this);

                NetworkHelper.getInstance().registerConnectivityReceiver(this);

                JAnalyticsInterface.init(this);
                JAnalyticsInterface.setDebugMode(!BuildConfig.IS_RELEASE);

                iwxapi = WXAPIFactory.createWXAPI(getApplicationContext(), weixin_appid, true);
                iwxapi.registerApp(weixin_appid);

                // 统计
                //Grab.initialize(this, UrlHelper.getGrabUrl(), grab_appid, grab_secret, AppUtil.getChannel(this));

                // 秒编译（阿里巴巴）
                //FreelineCore.init(this, getInstance());

                // 初始化wifi接口
                //WifiHelper.initialize(this);

                ActivityHelper.getInstance().setActivityStatusListener(this);

                SharePrefUtil.save4gstautus(this, false);

                DownloadM3u8Controller.getInstance().refreshAll(this);

//                refreshTokenData(new FinishListener() {
//                    @Override
//                    public void onFinish() {
//
//                    }
//                });

                BlockCanary.install(this, new BlockCanaryContext()).start();
            }

            UmengPushHelper.getInstance().init(getApplicationContext());
            //BuglyHelper.getInstance().init(getApplicationContext());
            //checkUpgrade();//检查版本更新

            String mGatewayURL = "https://cws.conviva.com/";
            String customerKey = "96a072dcde7a4939e4b6972696c5481bfe19bb9b";
            //ConvivaSessionManager.initClient(this, mGatewayURL, customerKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public P2PSMgr getP2PSMgr() {
//        return p2PSMgr;
//    }

    public IWXAPI getIwxapi() {
        return iwxapi;
    }


    public Context getContext() {
        return getBaseContext();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        AppDatabase.getInstance(this).closeDb();
        NetworkHelper.getInstance().removeListener(null);
        NetworkHelper.getInstance().unregisterConnectivityReceiver(this);
        SharePrefUtil.save4gstautus(this, false);
        SharePrefUtil.clearWechatUser(this);
    }


    @Override
    public void background() {
        //WifiHelper.stopScan();
    }

    @Override
    public void forground() {
        //WifiHelper.getInstance().checkWifiResume(getContext());
    }


    @Override
    public void exitApp() {
        // 清除所有线程操作
        ThreadHelper.destroy();
        DownloadM3u8Controller.getInstance().pauseAll(this);
        SharePrefUtil.save4gstautus(this, false);
    }

    /**
     * 获取当前进程名
     */
    private String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }

    /**
     * 包名判断是否为主进程
     *
     * @param
     * @return
     */
    public boolean isMainProcess() {
        return getApplicationContext().getPackageName().equals(getCurrentProcessName());
    }

}
